import { useMemberStore } from '@/stores'

const baseUrl = 'https://www.test.com'

const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
    }
    options.timeout = 600000
    const memberStore = useMemberStore()
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
      Authorization: memberStore.profile?.token,
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: String
  msg: String
  result: T
}
const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        resolve(res.data as Data<T>)
      },
      fail: reject,
    })
  })
}

export default http
